import xml.etree.ElementTree as ET
import json
import os

precise_repo_xts = "ability_ability_base,arkui_napi"
manifest_home = "./"
home = "./"
precise_gni_name = "precise_run.gni"

def getbundname (precise_repo_xts_list):
    # 遍历XML文件内容
    manifest_xml_list1 = []
    for child in ET.parse(manifest_home + "manifest.xml").getroot().findall('include'):
        manifest_xml_list1 += [manifest_home+"manifests/"+child.attrib['name']]
    print (manifest_xml_list1)
    manifest_xml_list2 = []
    path_list = []
    for xml in manifest_xml_list1:
        root = ET.parse(xml).getroot()
        if root.find('include') is not None:
            print ("in include")
            for child in root.findall('include'):
                manifest_xml_list2.append(manifest_home + "manifests/" + child.attrib['name'])
        else:
            print ("in else")
            for child in ET.parse(xml).getroot().findall('project'):
                if child.attrib['name'] in precise_repo_xts_list and len(precise_repo_xts_list) != 0:
                    path_list.append(child.attrib['path'] + "/bundle.json")
                    precise_repo_xts_list.remove(child.attrib['name'])
    print (manifest_xml_list2)
    print (path_list)
    if len(manifest_xml_list2) != 0 and  len(precise_repo_xts_list) != 0:
        for xml in manifest_xml_list2:
            for child in ET.parse(xml).getroot().findall('project'):
                if child.attrib['name'] in precise_repo_xts_list and len(precise_repo_xts_list) != 0:
                    path_list.append(child.attrib['path'] + "/bundle.json")
                    precise_repo_xts_list.remove(child.attrib['name'])
    print (path_list)
    bundle_list = []
    for path in path_list:
        # 读取JSON文件并获取指定key的value
        with open(home+path, 'r') as file:
            data = json.load(file)
        bundle_list.append(data['component']['name'])
    return bundle_list

def getdepends(bundlelist):
    depends_list = bundlelist
    for root, dirs, files in os.walk(home):
        for file in files:
            if file == 'bundle.json':
                # 构建完整的文件路径
                file_path = os.path.join(root, file)
                # 读取 JSON 文件并转换为 Python 对象
                with open(file_path, 'r') as f:
                    json_data = json.load(f)
                    bundle_name = json_data['component']['name']
                    if "deps" not in json_data['component']:
                        continue
                    if "components" in json_data['component']['deps']:
                        components_defs =  json_data['component']['deps']['components']
                        if len([element for element in bundlelist if element in components_defs]) != 0 and bundle_name not in depends_list:
                            depends_list.append(bundle_name)
                    if "third_party_defs" in json_data['component']['deps']:
                        third_party_defs = json_data['component']['deps']['third_party']
                        if len([element for element in bundlelist if element in third_party_defs]) != 0 and bundle_name not in depends_list:
                            depends_list.append(bundle_name)
    return depends_list

def write_precise_gni(depends_list):
    # 将数组转换为字符串形式，例如使用逗号分隔
    array_str = json.dumps(depends_list)

    # 打开文件并写入数组字符串
    with open(precise_gni_name, 'w') as file:
        file.write("precise_run=")
        file.write(array_str)

def run(precise_repo_xts_list):
    # 获取bundle_name_list
    bundlelist = getbundname(precise_repo_xts_list)
    print(bundlelist)
    # 获取全部需要跑的bundlename
    depends_list = getdepends(bundlelist)
    # depends_list = [
    #     "ffmpeg",
    #     "cast_engine",
    #     "build_framework",
    #     "liteos_m",
    #     "liteos_a",
    #     "runtime_core"
    # ],
    print(depends_list)
    # 写入gni文件
    write_precise_gni(depends_list)


if __name__ == '__main__':
    run(precise_repo_xts.split(','))